package cn.yuanqiao.common.utils;

/**
 * @ClassName: SnowflakeIdGenerator
 * @Description: 类的描述
 * @author: lihuahua
 * @date: 2024/3/8 9:51
 * @Blog: huahuacoco.top
 */

public class SnowflakeIdGenerator {
    // 开始时间戳 2022-01-01 00:00:00
    private final static long START_TIMESTAMP = 1640995200000L;

    // 每部分占用的位数
    private final static long SEQUENCE_BIT = 12; // 序列号占用的位数
    private final static long MACHINE_BIT = 5;   // 机器标识占用的位数
    private final static long DATACENTER_BIT = 5;// 数据中心占用的位数

    // 每部分最大值
    private final static long MAX_DATACENTER_NUM = ~(-1L << DATACENTER_BIT);
    private final static long MAX_MACHINE_NUM = ~(-1L << MACHINE_BIT);
    private final static long MAX_SEQUENCE = ~(-1L << SEQUENCE_BIT);

    // 每部分向左的位移
    private final static long MACHINE_LEFT = SEQUENCE_BIT;
    private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
    private final static long TIMESTAMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;

    private static long datacenterId = 1;  // 数据中心ID
    private static long machineId = 1;     // 机器标识ID
    private static long sequence = 0L; // 序列号
    private static long lastTimestamp = -1L; // 上次生成ID的时间戳

    public SnowflakeIdGenerator(long datacenterId, long machineId) {
        if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
            throw new IllegalArgumentException("Datacenter ID can't be greater than " + MAX_DATACENTER_NUM + " or less than 0");
        }
        if (machineId > MAX_MACHINE_NUM || machineId < 0) {
            throw new IllegalArgumentException("Machine ID can't be greater than " + MAX_MACHINE_NUM + " or less than 0");
        }
        SnowflakeIdGenerator.datacenterId = datacenterId;
        SnowflakeIdGenerator.machineId = machineId;
    }

    public static synchronized long generateId() {
        long timestamp = System.currentTimeMillis();
        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards, refusing to generate ID");
        }

        if (timestamp == lastTimestamp) { // 相同毫秒内，序列号自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            if (sequence == 0) {
                // 同一毫秒内的序列数已经达到最大，等待下一毫秒
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else { // 不同毫秒内，序列号重置
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        // 时间戳部分: 当前时间减去开始时间戳
        long timestampOffset = timestamp - START_TIMESTAMP;

        // 数据中心ID部分
        long datacenterIdOffset = datacenterId << DATACENTER_LEFT;

        // 机器标识部分
        long machineIdOffset = machineId << MACHINE_LEFT;

        // 序列号部分
        long sequenceOffset = sequence;

        // 最后拼装成64位的ID
        return timestampOffset << TIMESTAMP_LEFT |
                datacenterIdOffset |
                machineIdOffset |
                sequenceOffset;
    }

    private static long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }

    public static void main(String[] args) {
        // 创建SnowflakeIdGenerator实例，传入数据中心ID和机器标识ID
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
        // 生成ID
        long id = generateId();

        System.out.println(id);
    }
}
